import { getUsers, putUsers, deleteUsers } from '../../../services/api';

export default {
  namespace: 'member',

  state: {
    data: {
      list: [],
      pagination: {},
    },
  },

  effects: {
    *fetch({ payload: currentPage }, { call, put }) {
      const response = yield call(getUsers, 'member', currentPage);
      yield put({
        type: 'save',
        payload: response,
      });
    },
    *update({ payload, callback }, { call, put }) {
      const {
        phone,
        role,
        nickname,
        name,
        balance,
        receiverAddress,
        receiverName,
        receiverPhone,
      } = payload;
      const response = yield call(putUsers, payload.id, {
        phone,
        role,
        nickname,
        name,
        balance,
        receiverAddress,
        receiverName,
        receiverPhone,
      });
      yield put({
        type: 'replace',
        payload: {
          editableIndex: payload.editableIndex,
          response,
        },
      });
      if (callback) callback();
    },
    *remove({ payload, callback }, { call, put }) {
      const { currentIndex, id } = payload;
      yield call(deleteUsers, id);
      yield put({
        type: 'delete',
        payload: currentIndex,
      });
      if (callback) callback();
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    replace(state, action) {
      const { list } = state.data;
      list.splice(action.payload.editableIndex, 1, action.payload.response);
      return {
        ...state,
        data: {
          list,
          pagination: {
            ...state.data.pagination,
          },
        },
      };
    },
    delete(state, action) {
      const { list } = state.data;
      list.splice(action.payload, 1);
      const total = state.data.pagination.total - 1;
      return {
        ...state,
        data: {
          list,
          pagination: {
            ...state.data.pagination,
            total,
          },
        },
      };
    },
  },
};
